<template>
    <div class="city-wrapper" :class="{'inline fields':param.in_zip_inline,field:!param.in_zip_inline}">
        <label  for="">{{field.label}}</label>
        <div class="ui two column grid mycity">
            <fselect v-if="prov_data" class='column' :fname="`prov_code_${field.name}`" :data="prov_data" :val="prov"
                     @selectValsChange='selected_prov' placeholder="请选择省份" :editType="editType"></fselect>
            <fselect v-if="city_data" class='column' :fname="`city_code_${field.name}`" :data="city_data"
                     @selectValsChange='selected_city' :val="val" placeholder="请选择城市" :editType="editType"></fselect>
        </div>
        <draggable element="div" style="margin-top: 10px;" v-model="citys" :options="dragOptions" :move="onMove"
                   @start="isDragging=true" @end="isDragging=false" @change="hlChange">
            <transition-group type="transition" :name="'flip-list'" tag="div">

                <div v-for="(val,index) in citys" class="ui compact message" :key="index">
                    {{val.title}}<i @click="toRemove(index)" class="icon circular tiny remove"></i>
                </div>
            </transition-group>
        </draggable>
    </div>
</template>

<script type="text/ecmascript-6">
    import tool from 'src/util/tool';
    import util from '_util/index';
    import fselect from 'components/form/select'
    import draggable from 'vuedraggable'
    import _ from 'lodash'

    export default {
        data() {
            return {
                city: '',
                val: [],
                data: [],
                citys: [],
                prov: '',
                prov_name: '',

                prov_data: null,
                city_data: null,
                editable: true,
                isDragging: false,
                delayedDragging: false,
            }
        },
        methods: {

            toRemove(index) {
                this.citys.splice(index, 1);
            },
            hlChange() {
            },
            onMove({
                       relatedContext,
                       draggedContext
                   }) {
                const relatedElement = relatedContext.element;
                const draggedElement = draggedContext.element;
                let rl = relatedContext.list.length
                let reTitle = relatedElement ? relatedElement.title : ''
                if (rl == 1 && reTitle == '占位（请忽略）') {
                    relatedContext.list.splice(0, 1)
                }
                return true
            },
            selected_prov(val, fname, text) {

                if (val && util.isString(val)) {
                    this.prov = val
                    this.prov_name = text
                }


            },
            selected_city(val, fname, text) {
                if (val && util.isString(val)) {
                    if (val == -1) {
                        this.city_data.forEach(city => {
                            let ind = _.findIndex(this.citys, (o) => {
                                return o.code == city.id
                            });
                            if (ind == -1 && city.id != -1)
                                this.citys.push({
                                    prov: this.prov,
                                    prov_name: this.prov_name,
                                    code: city.id,
                                    title: city.title
                                })
                        });
                    } else {
                        let ck=_.find(this.city_data, city => {
                            return city.id == val
                        });
                        if(!ck)
                          return;

                        this.city = val
                        let ind = _.findIndex(this.citys, function (o) {
                            return o.code == val
                        })
                        if (ind == -1) {
                            if (this.field.city_type == 0)
                                this.citys = []
                            this.citys.push({
                                prov: this.prov,
                                prov_name: this.prov_name,
                                code: val,
                                title: text
                            })

                        }
                    }

                }
            },
            get_prov_data() {
                let url = tool.getApi(this, 'Get', 'getProv');
                let param = {};
                this.getData(url, param, 1)
            },
            get_city_data() {
                let url = tool.getApi(this, 'Get', 'getCity');
                let param = {
                    code: this.prov
                };
                this.getData(url, param, 0)
            },
            getData(url, param, type) {

                util.http.SR(this, url, param, null, (rs) => {
                    let data = rs.map(item => {
                        return {
                            id: item.code,
                            title: item.name
                        }
                    })

                    //显示全部
                    if (this.field.city_need_all && type == 0) {
                        data.push({
                            id: -1,
                            title: '全部'
                        })
                    }

                    if (type == 1) {
                        this.prov_data = data

                    } else {
                        this.city_data = data;

                    }
                });
            },
            myinit(){
                let fval = this.field.citys;
                if (fval) {
                    if (util.isArray(fval)) {
                        fval.map(city => {
                            this.citys.push(JSON.parse(city)[0]);
                        })
                    } else {
                        let arr = JSON.parse(fval) || [];
                        if (util.isArray(arr))
                            this.citys = arr;
                    }
                }
            }
        },
        watch: {
            _fval: function (val, old) {
                if (val != old) {
                    this.myinit()
                }
            },
            val: function (val, old) {
                if (val != old) {
                    this.$emit('setVo', this.field.name, JSON.stringify(this.val))
                }
            },
            citys: function (val, old) {
                let out = '';
                if (util.isArray(val)) {
                    if (val.length > 0) {
                        out = JSON.stringify(val)
                    }
                } else {
                    out = JSON.stringify(val)
                }
				this.$emit('onchange', { name: this.field.name, value:out})
                this.$emit('setVo', this.field.name, out)
            },
            prov: function (val, old) {
                if (val != old) {

                    this.get_city_data()
                }
            },
            isDragging(newValue) {
                if (newValue) {
                    this.delayedDragging = true
                    return
                }
                this.$nextTick(() => {
                    this.delayedDragging = false
                })
            }
        },
        components: {
            fselect,
            draggable
        },
        computed: {
//    data(){
//      let rs=this.citys.map(city=> {
//        return `${city.prov},${city.code},${city.title}`
//      })
//      return rs;
//    },
            _fval() {
                return this.field.fval;
            },
            dragOptions() {
                return {
                    animation: 0,
                    group: 'description',
                    disabled: !this.editable,
                    ghostClass: 'ghost'
                };
            },
            disableCity(){

            },
        },
        props: ['field', 'param', 'editType'],
        created() {
            this.myinit();

            this.get_prov_data()
        },
        mounted() {
        }
    };
</script>

<style rel="stylesheet/less" lang="less" scoped>
    @import "../../../common/style/mixin";

    @dir: "field/";
    .city-wrapper {

        .mycity {
            width: 500px;
        }
        .sortMenu();
        .messageIcon();
        .div_test {
            background-color: red;
            border: 1px solid black;
        }
    }

</style>
